library(data.table)
library(lubridate)
library(stringi)
library(stringr)
library(lfe)
library(car)
library(sandwich)
library(lmtest)
library(margins)
library(prediction)
library(ggplot2)
library(ggthemes)
library(scales)
library(stargazer)
# NB: stargazer should be installed with this fix: https://gist.github.com/alexeyknorre/b0780836f4cec04d41a863a683f91b53library(showtext)
library(showtext)

# Declare working directory beforehand in an environment variable
# IMPERIAL_LEGAL_POLITICS_REPLICATION_PATH = "path_to_your_folder"
# with the aid of usethis::edit_r_environ()
# Restart R session for the changes to take effect
path <- Sys.getenv("IMPERIAL_LEGAL_POLITICS_REPLICATION_PATH")
setwd(path)

# Load an object with case-instance-side-outcome-level data
# created by analysis/1b_prepare_crimea_data.r
load("data/crimea_case_outcomes_side_instance.rdata")

# Font for plotting
font_name <- "Arial"
showtext_auto()

##############################
# Prepare the data

# Create government win by instance object
government_win_instance <- crimea_case_outcomes_side_instance[involved_government == 1 & was_appealed == 1 & government == 1, list(government_win = max(win, na.rm = T)), by = c("caseid", "instanceLevel") ]

# Create federal agency win by instance object
federal_agency_win_instance <- crimea_case_outcomes_side_instance[involved_federal_agency == 1 & was_appealed == 1 & federal_agency == 1, list(federal_agency_win = max(win, na.rm = T)), by = c("caseid", "instanceLevel") ]

# Create regional/municipal agency win by instance object
regional_municipal_agency_win_instance <- crimea_case_outcomes_side_instance[ involved_regional_municipal_agency == 1 & was_appealed == 1 & ( regional_agency == 1 | municipal_agency == 1), list(regional_municipal_agency_win = max(win, na.rm = T)), by = c("caseid", "instanceLevel") ]

# Create local entity win (private disputes) by instance object
local_entity_win_instance <- crimea_case_outcomes_side_instance[ involved_government == 0 & local_entities_only == 0 & was_appealed == 1 & local_entity == 1, list(local_entity_win = max(win, na.rm = T)), by = c("caseid", "instanceLevel") ]

# Attach case characteristics of interest
case_chars <- c("caseid", "instanceLevel", "appeal", "presiding_judge_new", "presiding_judge_russian", "any_judge_new", "any_judge_russian", "year", "involved_federal_agency", "involved_regional_agency", "involved_municipal_agency", "involved_local_entity", "government_plaintiff", "federal_agency_plaintiff", "regional_agency_plaintiff", "municipal_agency_plaintiff", "local_entity_plaintiff", "caseTypeCode", "caseCategoryUnified", "caseCategoryRedux", "petty_case", "claimSum_deflated_wins_sinh", "presiding_judge", "lncountDocumentsByCourt", "lndays_elapsed", "local_entities_only", "dispute_type")

government_win_instance <- merge(government_win_instance, unique(crimea_case_outcomes_side_instance[, c(case_chars), with = F], by = c("caseid", "instanceLevel")), by = c("caseid", "instanceLevel"), all.x = T, all.y = F)
federal_agency_win_instance <- merge(federal_agency_win_instance, unique(crimea_case_outcomes_side_instance[, c(case_chars), with = F], by = c("caseid", "instanceLevel")), by = c("caseid", "instanceLevel"), all.x = T, all.y = F)
regional_municipal_agency_win_instance <- merge(regional_municipal_agency_win_instance, unique(crimea_case_outcomes_side_instance[, c(case_chars), with = F], by = c("caseid", "instanceLevel")), by = c("caseid", "instanceLevel"), all.x = T, all.y = F)
local_entity_win_instance <- merge(local_entity_win_instance, unique(crimea_case_outcomes_side_instance[, c(case_chars), with = F], by = c("caseid", "instanceLevel")), by = c("caseid", "instanceLevel"), all.x = T, all.y = F)

##############################
# Fit TWFE regressions
# for government advantage

government_twfe_formula_basic_newjudge <- as.formula("government_win ~ any_judge_new + appeal | caseid | 0 | presiding_judge")
government_twfe_formula_interacted_newjudge <- as.formula("government_win ~ any_judge_new*appeal | caseid | 0 | presiding_judge")

government_twfe_formula_basic_russianjudge <- as.formula("government_win ~ any_judge_russian + appeal | caseid | 0 | presiding_judge")
government_twfe_formula_interacted_russianjudge <- as.formula("government_win ~ any_judge_russian*appeal | caseid | 0 | presiding_judge")

## All non-petty cases
fit_government_twfe_newjudge_basic_nonpetty <- felm(government_twfe_formula_basic_newjudge, data = government_win_instance[ petty_case == 0 ])
fit_government_twfe_newjudge_interacted_nonpetty <- felm(government_twfe_formula_interacted_newjudge, data = government_win_instance[ petty_case == 0 ])

fit_government_twfe_russianjudge_basic_nonpetty <- felm(government_twfe_formula_basic_russianjudge, data = government_win_instance[ petty_case == 0 ])
fit_government_twfe_russianjudge_interacted_nonpetty <- felm(government_twfe_formula_interacted_russianjudge, data = government_win_instance[ petty_case == 0 ])

##############################
# Fit TWFE regressions
# for local entity advantage

local_entity_twfe_formula_basic_newjudge <- as.formula("local_entity_win ~ any_judge_new + appeal | caseid | 0 | presiding_judge")
local_entity_twfe_formula_interacted_newjudge <- as.formula("local_entity_win ~ any_judge_new*appeal | caseid | 0 | presiding_judge")

local_entity_twfe_formula_basic_russianjudge <- as.formula("local_entity_win ~ any_judge_russian + appeal | caseid | 0 | presiding_judge")
local_entity_twfe_formula_interacted_russianjudge <- as.formula("local_entity_win ~ any_judge_russian*appeal | caseid | 0 | presiding_judge")

# All nonpetty cases
fit_local_entity_twfe_newjudge_basic_nonpetty <- felm(local_entity_twfe_formula_basic_newjudge, data = local_entity_win_instance[ petty_case == 0 ])
fit_local_entity_twfe_newjudge_interacted_nonpetty <- felm(local_entity_twfe_formula_interacted_newjudge, data = local_entity_win_instance[ petty_case == 0 ])

fit_local_entity_twfe_russianjudge_basic_nonpetty <- felm(local_entity_twfe_formula_basic_russianjudge, data = local_entity_win_instance[ petty_case == 0 ])
fit_local_entity_twfe_russianjudge_interacted_nonpetty <- felm(local_entity_twfe_formula_interacted_russianjudge, data = local_entity_win_instance[ petty_case == 0 ])

##############################
# Fit TWFE regressions
# for government advantage at different
# levels of government

###
# Federal agencies
federal_agency_twfe_formula_basic_newjudge <- as.formula("federal_agency_win ~ any_judge_new + appeal | caseid | 0 | presiding_judge")
federal_agency_twfe_formula_interacted_newjudge <- as.formula("federal_agency_win ~ any_judge_new*appeal | caseid | 0 | presiding_judge")

federal_agency_twfe_formula_basic_russianjudge <- as.formula("federal_agency_win ~ any_judge_russian + appeal | caseid | 0 | presiding_judge")
federal_agency_twfe_formula_interacted_russianjudge <- as.formula("federal_agency_win ~ any_judge_russian*appeal | caseid | 0 | presiding_judge")

## All non-petty cases
fit_federal_agency_twfe_newjudge_basic_nonpetty <- felm(federal_agency_twfe_formula_basic_newjudge, data = federal_agency_win_instance[ petty_case == 0 ])
fit_federal_agency_twfe_newjudge_interacted_nonpetty <- felm(federal_agency_twfe_formula_interacted_newjudge, data = federal_agency_win_instance[ petty_case == 0 ])

fit_federal_agency_twfe_russianjudge_basic_nonpetty <- felm(federal_agency_twfe_formula_basic_russianjudge, data = federal_agency_win_instance[ petty_case == 0 ])
fit_federal_agency_twfe_russianjudge_interacted_nonpetty <- felm(federal_agency_twfe_formula_interacted_russianjudge, data = federal_agency_win_instance[ petty_case == 0 ])

###
# Regional/municipal agencies
regional_municipal_agency_twfe_formula_basic_newjudge <- as.formula("regional_municipal_agency_win ~ any_judge_new + appeal | caseid | 0 | presiding_judge")
regional_municipal_agency_twfe_formula_interacted_newjudge <- as.formula("regional_municipal_agency_win ~ any_judge_new*appeal | caseid | 0 | presiding_judge")

regional_municipal_agency_twfe_formula_basic_russianjudge <- as.formula("regional_municipal_agency_win ~ any_judge_russian + appeal | caseid | 0 | presiding_judge")
regional_municipal_agency_twfe_formula_interacted_russianjudge <- as.formula("regional_municipal_agency_win ~ any_judge_russian*appeal | caseid | 0 | presiding_judge")

## All non-petty cases
fit_regional_municipal_agency_twfe_newjudge_basic_nonpetty <- felm(regional_municipal_agency_twfe_formula_basic_newjudge, data = regional_municipal_agency_win_instance[ petty_case == 0 ])
fit_regional_municipal_agency_twfe_newjudge_interacted_nonpetty <- felm(regional_municipal_agency_twfe_formula_interacted_newjudge, data = regional_municipal_agency_win_instance[ petty_case == 0 ])

fit_regional_municipal_agency_twfe_russianjudge_basic_nonpetty <- felm(regional_municipal_agency_twfe_formula_basic_russianjudge, data = regional_municipal_agency_win_instance[ petty_case == 0 ])
fit_regional_municipal_agency_twfe_russianjudge_interacted_nonpetty <- felm(regional_municipal_agency_twfe_formula_interacted_russianjudge, data = regional_municipal_agency_win_instance[ petty_case == 0 ])

##############################
# TABLE 3. Within-case advantage regression: Government vs. Private disputes, Federal agency vs. Private disputes, Regional/Municipal agency vs. Private disputes, and Private disputes where one of the parties is not local, Crimea courts of first instance or appellate courts, 2014–2019, non-petty cases only

table_twfe_all <- stargazer(fit_government_twfe_russianjudge_basic_nonpetty, fit_government_twfe_russianjudge_interacted_nonpetty, fit_federal_agency_twfe_russianjudge_basic_nonpetty, fit_federal_agency_twfe_russianjudge_interacted_nonpetty, fit_regional_municipal_agency_twfe_russianjudge_basic_nonpetty, fit_regional_municipal_agency_twfe_russianjudge_interacted_nonpetty, fit_local_entity_twfe_russianjudge_basic_nonpetty, fit_local_entity_twfe_russianjudge_interacted_nonpetty, align = F, dep.var.labels = "", covariate.labels = c("Russian judge", "Appeals", "Appeals $\\times$ Russian judge"), column.labels = c("Government", "Federal agency", "Reg/mun agency", "Local entity"), column.separate = c(2), no.space = T, keep.stat = c("n", "rsq"), add.lines = list(c("Case type", rep("non-petty", 8)), c("Case FE", rep("yes", 8)), c("Judge FE", rep("no", 8))), notes = "TBA", type = "latex", style = "ajps")
cat(paste(table_twfe_all, collapse = "\n"), file = "tables/table3_twfe_all.tex")

##############################
# Yearly regressions for plotting

# Init an object to store the result
twfe_yearly_coeffs <- data.table() 

for( y in 2015:2019 ) {
	
	# Only petty cases
	for( case_size in c(0) ) {
					
		# Debug: y <- 2019; case_type <- "civil"; case_size <- 0
		tryCatch({
			
			# Fit government advantage regressions
			out_government_newjudge <- felm(government_twfe_formula_interacted_newjudge, data = government_win_instance[ petty_case == case_size & year == y ])
			out_government_russianjudge <- felm(government_twfe_formula_interacted_russianjudge, data = government_win_instance[ petty_case == case_size & year == y ])
			
			# Fit local entity advantage regressions
			out_local_entity_newjudge <- felm(local_entity_twfe_formula_interacted_newjudge, data = local_entity_win_instance[ petty_case == case_size & year == y ])
			out_local_entity_russianjudge <- felm(local_entity_twfe_formula_interacted_russianjudge, data = local_entity_win_instance[ petty_case == case_size & year == y ])

			# Extract coefficients, SEs and CIs of
			# interaction term with delta method
			
			# Russian judge, government, first instance
			coeffs_government_russianjudge_first <- as.data.table(deltaMethod(coef(out_government_russianjudge), "any_judge_russian", vcov. = vcov(out_government_russianjudge)))
			setnames(coeffs_government_russianjudge_first, c("beta", "se", "lower", "upper"))
			coeffs_government_russianjudge_first <- data.table(dispute_type = "Government vs. Private", treatment = "Russian judge", tier = "First instance", coeffs_government_russianjudge_first)

			# Russian judge, government, appeals
			coeffs_government_russianjudge_appeals <- as.data.table(deltaMethod(coef(out_government_russianjudge), "any_judge_russian + appeal + `any_judge_russian:appeal`", vcov. = vcov(out_government_russianjudge)))
			setnames(coeffs_government_russianjudge_appeals, c("beta", "se", "lower", "upper"))
			coeffs_government_russianjudge_appeals <- data.table(dispute_type = "Government vs. Private", treatment = "Russian judge", tier = "Appeals", coeffs_government_russianjudge_appeals)

			# Russian judge, local entity, first instance
			coeffs_local_entity_russianjudge_first <- as.data.table(deltaMethod(coef(out_local_entity_russianjudge), "any_judge_russian", vcov. = vcov(out_local_entity_russianjudge)))
			setnames(coeffs_local_entity_russianjudge_first, c("beta", "se", "lower", "upper"))
			coeffs_local_entity_russianjudge_first <- data.table(dispute_type = "Private disputes, local vs non-local", treatment = "Russian judge", tier = "First instance", coeffs_local_entity_russianjudge_first)

			# Russian judge, local entity, appeals
			coeffs_local_entity_russianjudge_appeals <- as.data.table(deltaMethod(coef(out_local_entity_russianjudge), "any_judge_russian + appeal + `any_judge_russian:appeal`", vcov. = vcov(out_local_entity_russianjudge)))
			setnames(coeffs_local_entity_russianjudge_appeals, c("beta", "se", "lower", "upper"))
			coeffs_local_entity_russianjudge_appeals <- data.table(dispute_type = "Private disputes, local vs non-local", treatment = "Russian judge", tier = "Appeals", coeffs_local_entity_russianjudge_appeals)
			
			# Prepare an object to export
			out <- rbindlist(list(coeffs_government_russianjudge_first, coeffs_government_russianjudge_appeals, coeffs_local_entity_russianjudge_first, coeffs_local_entity_russianjudge_appeals))
			out <- data.table(year = y, out)
			
			# Add to the final object
			twfe_yearly_coeffs <- rbind(twfe_yearly_coeffs, out, fill = T)
			
		}, error = function(e) {})
		
	}
}

##############################
# FIGURE S4. Government/Local Entity advantage by court tier and year, Crimea courts of first instance or appellate courts, 2015–2019

advantage_byyear_plot <- ggplot(aes(x = year, y = beta), group = tier, color = tier, fill = tier, data = twfe_yearly_coeffs[ treatment == "Russian judge" ]) +
	geom_point(aes(color = tier)) +
	geom_line(aes(color = tier, linetype = tier)) +
	geom_ribbon(aes(ymin = lower, ymax = upper, group = tier, fill = tier), alpha = .2, linetype = 0) +
	geom_hline(yintercept = 0, color = "black") +
	scale_x_continuous(expand = c(0.07, 0)) +
	scale_y_continuous(label = function(x) scales::percent(x, accuracy = 1), breaks = pretty_breaks(n = 10)) +
	labs(y = "", x = "Case registration year", fill = "", color = "", linetype = "", shape = "") +
	facet_wrap( ~ dispute_type, scale = "free_y", strip.position = "left", labeller = as_labeller(c("Government vs. Private" = "Change in Government win probability for “Russian” judge", "Private disputes, local vs non-local" = "Change in Local entity win probability for “Russian” judge") )) +
	theme_minimal() +
	theme(legend.position = "bottom", legend.title = element_blank(), text = element_text(family = font_name, size = 12), legend.text = element_text(size = 12))

ggsave(advantage_byyear_plot, file = "figures/figureS4_advantage_byyear_plot.pdf", device = cairo_pdf, width = 8.75, height = 5)
